package com.jiyun.alipay.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.alipay.easysdk.factory.Factory;
import com.jiyun.alipay.service.PayService;
import com.jiyun.pojo.order.OrderCost;
import com.jiyun.pojo.order.OrderInformation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/pay")
@RestController
public class PayController {
    @Autowired
    private PayService payService;

    //       账号bwdcqo3726@sandbox.com
    @RequestMapping("/payMoney")
    public String paymoney(String orderId) throws AlipayApiException {
        //根据订单ID来查找该订单的信息
        OrderInformation order = payService.findOrderInformationById(orderId);
        //根据订单ID来查找订单花费的钱数
        OrderCost cost = payService.findOrderCostById(orderId);


        String passengerTotal;
        if (order.getOrderStatus() == 3) {
            passengerTotal = String.valueOf(3);
        } else {
            passengerTotal = String.valueOf(cost.getPassengerTotal());
        }
        //秘钥
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDf5rjlTrBcy79FlIdzIdbGZiQflC6wYeOGVtJb/bgr0J/+XXAQqB3tHGppoAhxAEWUcH2M7y8Mwcr5dmUPWR5o6G2XVEZsrkd9w46BRNYtgtXP91kuAgrg5ZQUJ3f3diBdhB/IG2LDTHZ6W+2W0JERccOTm8FofJ9kGu3i1K2ClOSFu8X2y/Sr+etjBcql4Duzvn3CMWs7FUXAPofsCfrtOLcciBz3pR5hHy1Y1edySTio2Rfa2eqcsuLrlrEw8WhyRz38j0r+EqxuK2PHTrD13h97Tj+N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UbjbnTPTzilpAPbxEknoZmy3AhEJlAoGAKYhKmXUjF7pvoi6bxlm3dapNOmee0+4ARwozSwyt+vu7Pv5yaXK/GhS7xTvcpPqP86Lpxrc0Vk8OCAeFf62jtm/DkBbJyr3B78ImMaDHQZcOyJXBQMR5E6XCoOBWbKTBiFBF/0SmqMWkwYit3OsEzH4jFHMsyCwWiTArSE9c2oc=";
        //key
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3+a45U6wXMu/RZSHcyHWxmYkH5QusGHjhlbSW/24K9Cf/l1wEKgd7RxqaaAIcQBFlHB9jO8vDMHK+XZlD1keaOhtl1RGbK5HfcOOgUTWLYLVz/dZLgIK4OWUFCd393YgXYQfyBtiw0x2elvtltCREXHDk5vBaHyfZBrt4tStgpTkhbvF9sv0q/nrYwXKpeA7s759wjFrOxVFwD6H7An67Ti3HIgc96UeYR8tWNXnckk4qNkX2tnqnLLi65axMPFockc9/I9K/hKsbitjx06w9d4fe04/jcbDcZ9ArLCvuU94mmbTOiYvXpJITpNbnKxXDBS1wwINId/iBcWYmJNpoQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000140608138");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

//        request.setNotifyUrl("http://kvbkmy.natappfree.cc/alipay/pay/notify");

        //支付成功返回页面
        request.setReturnUrl("http://localhost:8080/overPayment");

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        //订单号
        model.setOutTradeNo(order.getOrderId());
        //钱数
        model.setTotalAmount(passengerTotal);
        //支付页面标题
        model.setSubject("支付乘车费用");
        model.setProductCode("QUICK_WAP_WAY");
        //收款账号
        model.setSellerId("2088721041616064");
        request.setBizModel(model);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }


    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            System.out.println(tradeNo);
            System.out.println(gmtPayment);
            System.out.println(alipayTradeNo);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单状态

            }
        }
        return "success";
    }

}


